/**
 * Copyright (C), 2019-2020,个人开发
 * 文件名: ZgbSsoWebFilter
 * 作者: lsyzx【892366102@qq.com】
 * 创建时间: 2019/2/24 15:05
 */
package com.zx.sso.core.filter;

import cn.hutool.core.util.StrUtil;
import com.zx.sso.core.conf.Conf;
import com.zx.sso.core.login.SsoWebLoginHelper;
import com.zx.sso.core.user.ZxSsoUser;
import com.zx.sso.core.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作者: lsyzx【zhux@zhengebang.com】
 * 创建时间: 2019/2/24 15:05
 * 描述: web单点登录过滤器
 * 历史修改:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Slf4j
public class ZxSsoWebFilter extends HttpServlet implements Filter {

    private String ssoServer;
    private String logoutPath;
    private String excludedPaths;
    private String sysCode;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        ssoServer = filterConfig.getInitParameter(Conf.SSO_SERVER);
        logoutPath = filterConfig.getInitParameter(Conf.SSO_LOGOUT_PATH);
        excludedPaths = filterConfig.getInitParameter(Conf.SSO_EXCLUDED_PATHS);
        sysCode = filterConfig.getInitParameter(Conf.SYSCODE);
        log.info("XxlSsoWebFilter init.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // make url

        String servletPath = req.getServletPath();

        // excluded path check
        if (StringUtils.checkexcludedPaths(excludedPaths, servletPath)) {
            // excluded path, allow
            chain.doFilter(request, response);
            return;
        }

        // logout path check
        if (logoutPath != null
                && logoutPath.trim().length() > 0
                && logoutPath.equals(servletPath)) {

            // remove cookie
            SsoWebLoginHelper.removeSessionIdByCookie(req, res);
            String redirect_url = req.getParameter(Conf.REDIRECT_URL);
            String logoutPageUrl = ssoServer.concat(Conf.SSO_LOGOUT);
            if (StrUtil.isNotEmpty(redirect_url)) {
                logoutPageUrl = ssoServer.concat(Conf.SSO_LOGOUT) + "?" + Conf.REDIRECT_URL + "=" + redirect_url;
            }
            // redirect logout
            res.sendRedirect(logoutPageUrl);

            return;
        }

        // valid login user, cookie + redirect
        ZxSsoUser xxlUser = SsoWebLoginHelper.loginCheck(req, res);

        // valid login fail
        if (xxlUser == null) {

            String header = req.getHeader("content-type");
            boolean isJson = header != null && header.contains("json");
            if (isJson) {

                // json msg
                res.setContentType("application/json;charset=utf-8");
                res.getWriter().println("{\"code\":" + Conf.SSO_LOGIN_FAIL_RESULT.getCode() + ", \"msg\":\"" + Conf.SSO_LOGIN_FAIL_RESULT.getMsg() + "\"}");
                return;
            } else {

                // total link
                String link = req.getRequestURL().toString();

                // redirect logout
                String loginPageUrl = ssoServer.concat(Conf.SSO_LOGIN)
                        + "?" + Conf.REDIRECT_URL + "=" + link;

                res.sendRedirect(loginPageUrl);
                return;
            }

        }

        // ser sso user
        request.setAttribute(Conf.SSO_USER, xxlUser);


        // already login, allow
        chain.doFilter(request, response);
        return;
    }

}
